/**
 * 安全日志配置
 * EndoSight-UC 医疗AI系统
 */

import winston from 'winston';
import fs from 'fs';
import path from 'path';

// 确保日志目录存在
const logDir = './logs';
if (!fs.existsSync(logDir)) {
  fs.mkdirSync(logDir, { recursive: true });
}

// 安全日志格式化器
const secureFormat = winston.format.combine(
  winston.format.timestamp(),
  winston.format.errors({ stack: true }),
  winston.format.json(),
  winston.format.printf(({ timestamp, level, message, service, userId, sessionId, ...meta }) => {
    const logEntry = {
      timestamp,
      level: level.toUpperCase(),
      message,
      service: service || 'endo_sight_uc',
      userId: userId || 'system',
      sessionId: sessionId || 'system',
      ...meta
    };

    // 移除敏感信息
    if (logEntry.password) delete logEntry.password;
    if (logEntry.token) delete logEntry.token;
    if (logEntry.apiKey) delete logEntry.apiKey;

    return JSON.stringify(logEntry);
  })
);

// 创建安全日志记录器
const secureLogger = winston.createLogger({
  level: process.env.LOG_LEVEL || 'info',
  format: secureFormat,
  transports: [
    // 控制台输出
    new winston.transports.Console({
      format: winston.format.combine(
        winston.format.colorize(),
        winston.format.simple()
      )
    }),

    // 文件输出 - 一般日志
    new winston.transports.File({
      filename: path.join(logDir, 'secure.log'),
      maxsize: 10 * 1024 * 1024, // 10MB
      maxFiles: 5,
      format: secureFormat
    }),

    // 文件输出 - 错误日志
    new winston.transports.File({
      filename: path.join(logDir, 'secure-error.log'),
      level: 'error',
      maxsize: 10 * 1024 * 1024, // 10MB
      maxFiles: 5,
      format: secureFormat
    })
  ],

  // 异常处理
  exceptionHandlers: [
    new winston.transports.File({
      filename: path.join(logDir, 'secure-exceptions.log')
    })
  ],

  // 拒绝处理
  rejectionHandlers: [
    new winston.transports.File({
      filename: path.join(logDir, 'secure-rejections.log')
    })
  ]
});

// 开发环境配置
if (process.env.NODE_ENV === 'development') {
  secureLogger.add(new winston.transports.Console({
    format: winston.format.combine(
      winston.format.colorize(),
      winston.format.simple()
    )
  }));
}

// 创建特定模块的日志记录器
export const createSecureLogger = (module) => {
  return secureLogger.child({ module });
};

// 敏感操作日志记录器
export const auditLogger = secureLogger.child({
  type: 'audit',
  compliance: 'HIPAA'
});

// 性能日志记录器
export const performanceLogger = secureLogger.child({
  type: 'performance'
});

// 安全事件日志记录器
export const securityLogger = secureLogger.child({
  type: 'security',
  compliance: 'HIPAA'
});

export default secureLogger;